package com.novellotus.iov.carvice.model;

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.activity.AddFailureActivity;
import com.novellotus.iov.carvice.bean.JsonServiceBean;
import com.novellotus.iov.carvice.bean.RxCarCheckBean;
import com.novellotus.iov.carvice.retrofit.BaseEntity;
import com.novellotus.iov.carvice.retrofit.BaseObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.utils.DataSign;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.MyViewUtils;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;
import com.rengwuxian.materialedittext.MaterialEditText;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function5;
import okhttp3.RequestBody;


/**
 * Created by Rich on 2017/8/25.
 * 添加报表处理类
 */

public class AddServiceModel {

    private AddFailureActivity context;
    private AddServiceModelInterface addServiceModelInterface;
    private Observable<CharSequence> observablePlate;
    private Observable<CharSequence> observableLocation;
    private Observable<CharSequence> observableName;
    private Observable<CharSequence> observableMobile;
    private Observable<CharSequence> observableDetail;
//    private Observable<CharSequence> observableFault;
//    private Observable<CharSequence> observableMark;

    private String plate = "";
    private String location = "";
    private String name = "";
    private String mobile = "";
    private String des = "";

    public AddServiceModel(AddFailureActivity addServiceActivity, AddServiceModelInterface addServiceModelInterface) {
        this.context = addServiceActivity;
        this.addServiceModelInterface = addServiceModelInterface;
    }

    /**
     * @param edit 设置车牌编辑框
     */
    public void setPlateEdit(final MaterialEditText edit) {
        observablePlate = RxTextView.textChanges(edit);
        observablePlate.compose(RxSchedulers.<CharSequence>lifecycle(context)).compose(RxSchedulers.<CharSequence>compose()).subscribe(new Consumer<CharSequence>() {
            @Override
            public void accept(CharSequence charSequence) throws Exception {
                plate = charSequence.toString();
                if (charSequence.length() >= 7) {
                    if (MyUtils.isPlate(charSequence.toString())) {
                        edit.setError(null);
                    } else {
                        edit.setError("车牌号格式有误");
                    }
                }

            }
        });

    }

    /**
     * @param edit 设置定位编辑框
     */
    public void setLocationEdit(final TextView edit) {
        observableLocation = RxTextView.textChanges(edit);
        observableLocation.compose(RxSchedulers.<CharSequence>lifecycle(context))
                .subscribe(new Consumer<CharSequence>() {
                    @Override
                    public void accept(CharSequence charSequence) throws Exception {
                        location = charSequence.toString();
                    }
                });
    }


    /**
     * @param edit 设置昵称编辑框
     */
    public void setNameEdit(final EditText edit) {
        observableName = RxTextView.textChanges(edit);
        observableName.compose(RxSchedulers.<CharSequence>lifecycle(context))
                .subscribe(new Consumer<CharSequence>() {
                    @Override
                    public void accept(CharSequence charSequence) throws Exception {
                        name = charSequence.toString();
                    }
                });
    }

    /**
     * @param edit 设置手机号编辑框
     */
    public void setMobileEdit(final EditText edit) {
        observableMobile = RxTextView.textChanges(edit);
        observableMobile.compose(RxSchedulers.<CharSequence>lifecycle(context))
                .subscribe(new Consumer<CharSequence>() {
                    @Override
                    public void accept(CharSequence charSequence) throws Exception {
                        mobile = charSequence.toString();
                    }
                });
    }

    /**
     * @param editText 故障描述
     */
    public void setDetailEdit(EditText editText) {
        observableDetail = RxTextView.textChanges(editText);
        observableDetail.compose(RxSchedulers.<CharSequence>lifecycle(context))
                .subscribe(new Consumer<CharSequence>() {
                    @Override
                    public void accept(CharSequence charSequence) throws Exception {
                        des = charSequence.toString();
                    }
                });

    }


    /**
     * 表单验证
     */
    public void confirm(final Button button) {

        Observable.combineLatest(observablePlate, observableName, observableMobile, observableLocation, observableDetail, new Function5<CharSequence, CharSequence, CharSequence, CharSequence, CharSequence, Boolean>() {
            @Override
            public Boolean apply(CharSequence plate, CharSequence name, CharSequence mobile, CharSequence location, CharSequence detail) throws Exception {
                return MyUtils.isPlate(plate.toString()) && name.length() > 0 && MyUtils.isMobile(mobile.toString()) && location.length() > 0 && detail.length() > 0;
            }
        }).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean pass) throws Exception {
                if (pass) {
                    MyViewUtils.setButtonClickable(button, true);
                } else {
                    MyViewUtils.setButtonClickable(button, false);
                }
            }
        });
    }

    /**
     * 设置提交按钮
     * json:{pn:'',linkman:'',phone:'',remark:'',address:'',lat:'',lng:'',flauts:['key']}
     */
    String[] flauts;

    public void setKeys(String[] flauts) {
        this.flauts = flauts;
    }

    private String getKesys() {
        String str = "";
        for (String s : flauts) {
            if (str.length() == 0) {
                str += s;
            } else {
                str += "," + s;
            }
        }
        return str;
    }

    double lat, lng;

    public void setLocation(double lat, double lng) {
        this.lat = lat;
        this.lng = lng;
    }


    /**
     * @param button 提交售后维修
     */
    public void setSubmitBtn(Button button) {
        RxView.clicks(button).compose(RxSchedulers.lifecycle(context)).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                JsonServiceBean jsonServiceBean = new JsonServiceBean();
                jsonServiceBean.setPn(plate);
                jsonServiceBean.setLinkman(name);
                jsonServiceBean.setMobile(mobile);
                jsonServiceBean.setAddress(location);
                jsonServiceBean.setLat(lat);
                jsonServiceBean.setLng(lng);
                jsonServiceBean.setRemark(des);
                Gson gson = new Gson();
                RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), gson.toJson(jsonServiceBean));
                Observable<BaseEntity<Object>> observable = RetrofitFactory.getInstance().fault(SharedPreferencesUtils.getKey(context)[0], body);
                observable.compose(RxSchedulers.<BaseEntity<Object>>lifecycle(context))
                        .compose(RxSchedulers.<BaseEntity<Object>>compose())
                        .subscribe(new BaseObserver<Object>(context) {
                            @Override
                            public void onSuccess(Object response) {
                                MyUtils.showToast(context, "提交成功!");
                                context.finish();
                            }

                            @Override
                            public void onFail(int code, String msg) {
                                MyUtils.showToast(context, msg);
                            }

                            @Override
                            public void onError(String msg) {
                                MyUtils.showToast(context, msg);
                            }
                        });
            }

        });
    }

    public interface AddServiceModelInterface {
        void checkPass(RxCarCheckBean response);

        void updateMarkerCount(int count);
    }
}
